// my/pages/changePwd/changePwd.js
Page({
    data: {
      oldPwd: '',
      newPwd: '',
      confirmPwd: '',
      username: '' // 假设已登录，用户名可从全局或本地获取
    },
  
    onInputOldPwd(e) {
      this.setData({ oldPwd: e.detail.value });
    },
    onInputNewPwd(e) {
      this.setData({ newPwd: e.detail.value });
    },
    onInputConfirmPwd(e) {
      this.setData({ confirmPwd: e.detail.value });
    },
    onLoad() {
      // 获取全局用户信息
      const app = getApp();
      if (app.globalData.inputUserInfo && app.globalData.inputUserInfo.userName) {
        this.setData({
          username: app.globalData.inputUserInfo.userName
        });
      } else {
        // 可以考虑从本地缓存获取
        const userInfo = wx.getStorageSync('inputUserInfo');
        if (userInfo && userInfo.userName) {
          this.setData({
            username: userInfo.userName
          });
        }
      }
    },
    onSubmit(e) {
      const { oldPwd, newPwd, confirmPwd, username } = this.data;
       // 打印用户名和原密码
      console.log('username:', username, 'oldPwd:', oldPwd);
      if (!oldPwd || !newPwd || !confirmPwd) {
        wx.showToast({ title: '请填写完整', icon: 'none' });
        return;
      }
      if (newPwd !== confirmPwd) {
        wx.showToast({ title: '两次新密码不一致', icon: 'none' });
        return;
      }
      // 1. 校验原密码（用登录接口）
      wx.request({
        url: 'http://localhost:8080/auth/login',
        method: 'POST',
        data: {
          username:this.data.username, 
          password: this.data.oldPwd,
          source: 2 // 小程序
        },
        success: (res) => {
          if (res.data.code === 200) {
            // 2. 原密码正确，调用修改密码接口
            wx.request({
              url: 'http://localhost:8080/auth/changePwd', // 假设有这个接口
              method: 'POST',
              data: {
                username,
                newPwd
              },
              success: (res2) => {
                if (res2.data.code === 200) {
                  wx.showToast({ title: '修改成功', icon: 'success' });
                  setTimeout(() => {
                    wx.switchTab({ url: '/pages/my/my' });
                  }, 1000);
                } else {
                  wx.showToast({ title: res2.data.message || '修改失败', icon: 'none' });
                }
              }
            });
          } else {
            wx.showToast({ title: '原密码错误', icon: 'none' });
          }
        }
      });
    },
  
    onCancel() {
      wx.switchTab({ url: '/pages/my/my' });
    }
  });